<template>
  <div style="display: flex;flex-direction: column;width: 100vw;">
    <div style="height: 60px;display: flex;align-items: center;justify-content: center;">
      <el-alert
          title="提示"
          description="选择相应的项目分类、业务分类、规范后，上传某次招标文件，以您选择的招标规范为依据，可以自动检测出哪些招标项是此次招标活动中的必填要素，进行标识，以便您编写投标文件。"
          type="info"
          show-icon/>
    </div>

    <div style="display: flex;align-items:center;margin-top: 2%">

      <!--   项目分类   -->
      <el-form :model="data.industry">
        <el-form-item style="margin-left: 50px;" label-width="80" label="项目分类">
          <el-select v-model="data.selectIndustryId" placeholder="请选择项目分类" style="width: 20vw" @change="LoadDomain">
            <el-option
                v-for="item in data.industry"
                :key="item.industryId"
                :label="item.industryName"
                :value="item.industryId"
            >
              <span style="float: left">{{ item.industryName }}</span>
              <span
                  style="float: right; color: var(--el-text-color-secondary); font-size: 13px;"
              >{{ item.description }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!--业务分类-->
      <el-form :model="data.domain">
        <el-form-item style="margin-left: 50px;" label-width="80" label="业务分类">
          <el-select v-model="data.selectFieldId" placeholder="请选择业务分类" style="width: 20vw" @change="LoadSpec">
            <el-option
                v-for="item in data.domain"
                :key="item.fieldId"
                :label="item.fieldName"
                :value="item.fieldId"
            >
              <span style="float: left">{{ item.fieldName }}</span>
              <span
                  style="float: right; color: var(--el-text-color-secondary); font-size: 13px;"
              >{{ item.description }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>


      <!--规范-->
      <el-form :model="data.Spec">
        <el-form-item style="margin-left: 50px;" label-width="40" label="规范">
          <el-select v-model="data.selectSpecId" placeholder="请选择规范" style="width: 20vw">
            <el-option
                v-for="item in data.Spec"
                :key="item.specId"
                :label="item.specName"
                :value="item.specId"
            >
              <span style="float: left">{{ item.specName }}</span>
              <span
                  style="float: right; color: var(--el-text-color-secondary); font-size: 13px;"
              >{{ item.description }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

    </div>

    <div style="margin-top: 2%">
      <el-upload
          class="upload-demo"
          drag
          :action="uploadAction"
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">
          拖拽pdf文件到此处或者 <em>点击上传</em>
        </div>
      </el-upload>
    </div>


    <el-button v-if="data.downLoad" type="primary" @click="downloadFile">下载</el-button>

  </div>
</template>

<script setup>
import {UploadFilled} from '@element-plus/icons-vue'
import {computed, reactive} from "vue";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";
import {PYTHON_API_BASE_URL} from "@/config.js";

const data = reactive({
  industry: [],
  selectIndustryId: null,
  domain: [],
  selectFieldId: null,
  Spec: [],
  selectSpecId: null,
  downLoad: false,
  filename: "",
})

//加载所有行业
const Load = () => {
  request.get(`/java/industry/category/getAll`)
      .then((response) => {
        console.log("行业数据：", response);
        data.industry = response.data.records;
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
};

Load()


//加载行业下的领域
const LoadDomain = () => {
  data.domain = []
  data.selectFieldId = null
  // 仅当选择了一个行业时才发起请求
  if (data.selectIndustryId) {
    request.get(`/java/field/category/getFiledByIndustryId?IndustryId=${data.selectIndustryId}`)
        .then((response) => {
          console.log("行业下领域数据：", response);
          data.domain = response.data;
        })
        .catch((error) => {
          console.error('请求发生错误:', error);
        })
  }
};


//加载领域下的规范
const LoadSpec = () => {
  data.Spec = []
  data.selectSpecId = null
  // 仅当选择了一个行业时才发起请求
  if (data.selectFieldId) {
    request.get(`/java/specification/getSpeByFieldCategoryId?fieldCategoryId=${data.selectFieldId}`)
        .then((response) => {
          console.log("领域下规范的数据：", response);
          data.Spec = response.data;
        })
        .catch((error) => {
          console.error('请求发生错误:', error);
        })
  }
};

// 计算属性来构建包含ID的上传URL
const uploadAction = computed(() => {
  return PYTHON_API_BASE_URL +`/analysisFile/?SpecId=${data.selectSpecId}`;
});


// 实现beforeUpload方法
function beforeUpload(file) {
  if (data.selectIndustryId == null || data.selectFieldId == null || data.selectSpecId == null) {
    ElMessage.info("请选择行业、领域和规范后再上传文件")
    return false;
  }

  // 例如检查文件大小，不允许上传超过10MB的文件
  const isTooLarge = file.size / 1024 / 1024 > 100;
  if (isTooLarge) {
    // 使用Element UI的消息提示组件，显示错误信息
    ElMessage.error('文件大小不能超过 100MB!');
    return false;  // 拦截文件上传
  }

  // (可选) 还可以检查文件类型等其他条件
  const isPDF = file.type === 'application/pdf';
  if (!isPDF) {
    ElMessage.error('只能上传pdf文件!');
    return false;  // 拦截文件上传
  }

  // 如果通过了所有检查，则返回true或者没有返回值（implicit return undefined），允许上传继续
}


function handleSuccess(response, file, fileList) {
  // 在这里处理上传成功后的逻辑
  if (response.message) {
    ElMessage.info(response.message);
  }
  if (response.filename) {
    data.filename = response.filename
    data.downLoad = true
  }
}


const downloadFile = () => {
  request.getFile(PYTHON_API_BASE_URL + `/download/${data.filename}`).then(blob => {
    // 从Blob中创建一个URL对象
    const url = window.URL.createObjectURL(blob);

    // 创建一个链接并模拟点击以触发下载
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', data.filename); // 这里可以给文件命名
    document.body.appendChild(link);
    link.click();

    // 清理和移除链接元素
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }).catch(error => {
    // 错误处理
    console.error('下载文件时出现错误：', error);
    ElMessage.error('下载文件失败！');
  })
}

</script>

<style scoped>
.el-alert {
  margin: 20px 0 0;
}

.el-alert:first-child {
  margin: 0;
}
</style>